package com.tianhao.luo.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Callable来实现线程创建并获取到返回值
 *
 * @author tianhao.luo@hand-china.com
 */
public class CallableDemo1 {


    public static void main(String[] args) {
        // Runnable创建线程
        new Thread(new MyThread(), "aa").start();

        // callable创建线程
        //new Thread(new MyThread2(),"bb").start();
        FutureTask<String> stringFutureTask = new FutureTask<>(new MyThread2());
        try {
            // 开启子线程去执行callable方法
            new Thread(stringFutureTask,"bb").start();
            // 获取到返回值,注意这个get方法在没有获取到stringFutureTask的返回值前会阻塞
            while (!stringFutureTask.isDone()) {
                System.out.println(Thread.currentThread().getName()+" wait...");
                Thread.sleep(1000);
            }
            // 下面的两次get方法，我们能够发现，获取到的返回值是一样的，而且feature线程不会再执行一次
            String s = stringFutureTask.get();
            System.out.println("feature第一次获取结果:"+s);
            String s1 = stringFutureTask.get();
            System.out.println("feature第二次获取结果:"+s1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    static class MyThread implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+" 这是一个run方法");
        }
    }

    static class MyThread2 implements Callable<String> {
        @Override
        public String call() throws Exception {
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName()+" 这是call方法");
            return "call的返回值";
        }
    }
}
